/*
 * 开启严格模式
 */
"use strict";
$(function () {
    // 条件模板
    const branchTpl = `
    <div class="col-box">
        <div class="condition-node">
            <div class="condition-node-box">
                <div class="auto-judge">
                    <div class="sort-left">&lt;</div>
                    <div class="title-wrapper">
                        <span class="editable-title">条件 <i class="SN"></i></span>
                        <span class="priority-title">优先级 <i class="level"></i></span>
                        <i class="anticon anticon-close close" data-click="condition-close"></i>
                    </div>
                    <div class="sort-right">&gt;</div>
                    <div class="content" data-click="condition-setting">
                        <div id="div{{id}}">
                            <p class="placeholder">请设置条件</p>
                            <p class="placeholder">请设置条件</p>
                        </div>
                        <input type="hidden" name="condition[]" autocomplete="off" id="{{id}}" value="{}">
                        <input type="hidden" name="cid" autocomplete="off" value="{{id}}">
                    </div>
                </div>
                <!-- 添加节点 开始-->
                <div class="add-node-btn-box">
                    <div class="add-node-btn">
                        <!-- 添加节点符号 start-->
                        <button type="button" data-click="staff-add" class="btn">
                            <span class="iconfont"></span>
                        </button>
                        <!-- 添加节点符号 end-->
                    </div>
                </div>
                <!-- 添加节点 结束 -->
            </div>
        </div>
    </div>`

    // 显示添加条件弹窗
    const toolTpl = `
    <div role="tooltip" class="tooltip" tabindex="0" style="display: block;">
        <div class="add-node-popover-body">
            <a class="add-node-popover-item approver" data-click="approver">
                <div class="item-wrapper"><span class="iconfont"></span></div>
                <p>审批人</p>
            </a>
            <a class="add-node-popover-item notifier" data-click="notifier">
                <div class="item-wrapper"><span class="iconfont"></span></div>
                <p>抄送人</p>
            </a>
            <!--<a class="add-node-popover-item condition" click="condition">
                <div class="item-wrapper"><span class="iconfont"></span></div>
                <p>条件分支</p>
            </a>-->
            <div class="left_arrow"></div>
        </div>
    </div>`

    // 添加节点
    const addNodeTpl = `
    <div class="add-node-btn-box">
        <div class="add-node-btn">
            <button type="button" data-click="staff-add" class="btn"><span class="iconfont"></span></button>
        </div>
    </div>`

    // 左边界线 condition-node 后
    const leftLineTpl = `
    <div class="condition-cover-line">
        <div class="top-left-cover-line"></div>
        <div class="bottom-left-cover-line"></div>
    </div>`

    // 右边界线
    const rightLineTpl = `
    <div class="condition-cover-line">
        <div class="top-right-cover-line"></div>
        <div class="bottom-right-cover-line"></div>
    </div>`

    // 审批人
    const approverTpl = `
    <div class="condition-node">
        <div class="node-wrap">
            <div class="node-wrap-box">
                <div class="title {{type}}">
                    <span class="iconfont editable-icon">{{icon}}</span>
                    <span class="editable-title">{{title}}</span>
                    <i class="anticon anticon-close close" data-click="staff-close"></i>
                </div>
                <div class="content" data-click="{{type}}-setting">
                    <div class="text">
                        <span class="placeholder">{{text}}</span>
                        <div id="div{{id}}"></div>
                        <input id="{{id}}" type="hidden" name="node[]">
                    </div>
                    <i class="anticon anticon-right arrow"></i>
                </div>
            </div>
            ` + addNodeTpl + `
        </div>
    </div>`

    /**
     * 获取节点个数
     */
    function getNodeNum() {
        let obj = $('#main-node').find('.col-box')
        return obj.length
    }

    // 新增条件
    $('.add-branch').on('click', this, function () {
        let num = getNodeNum(),
            node = $('.branch-box .col-box:last'),
            id = rand()
        const reg = new RegExp('{{id}}', 'g')
        let html = branchTpl.replace(reg, id)
        node.before(html)
        if (num === 1) {
            $('#main-node').find('.branch-box').css({
                'border-bottom': '1px solid #ccc',
                'border-top': '1px solid #ccc',
                'min-height': 250,
            })
            let obj = $('#main-node').find('.branch-box .col-box:first .condition-node:first')
            obj.before(leftLineTpl)
            // 最后一个
            let endObj = $('#main-node').find('.branch-box .col-box:last .condition-node:last')
            endObj.before(rightLineTpl)
        }
    })

    // 删除条件
    $(document).on('click', '[data-click="condition-close"]', this, function () {
        const num = getNodeNum();
        switch (num) {
            case 1:
                // 至少保留一个
                return
                break;
            case 2:
                $('#main-node').find('.branch-box').css({
                    'border-bottom': 'none',
                    'border-top': 'none',
                    'min-height': 255,
                })
                break;
            default:
                break;
        }
        $(this).parents('.col-box').remove()
    })
    // 新增人员 弹窗
    $(document).on('click', '[data-click="staff-add"]', this, function () {
        // 判断提示框的个数
        const ele = $('#main-node').find('.tooltip')
        if (ele.length > 0) {
            ele.remove()
        }
        $(this).after(toolTpl)
        $('.tooltip').show()
    })

    // 选择人员
    $(document).on('click', '[data-click="staff-select"]', this, function () {
        let obj = $(this).find('[name="staff[]"]'),
            id = obj.attr('id')
        if ($(this).find('span.placeholder')) {
            $(this).find('span.placeholder').remove()
        }
        // 调用此方法需保证 当前页面有 js-party-select-result-list 和 该id 的隐藏域
        layer('examine', 'orgTree', {
            id: id,
            box: ''
        })
    })


    // 设置条件
    $(document).on('click', '[data-click="condition-setting"]', this, function () {
        let obj = $(this).find('[name="condition[]"]'),
            id = rand(),
            mid = $('[name="id"]').val(),
            value = ''
        if (obj.length > 0) {
            id = obj.attr('id')
            value = obj.val()
        } else {
            let tpl = `
            <input id="${id}" type="hidden" name="condition[]">`
            $(this).append(tpl)
            $(this).find('p.placeholder').remove()
        }

        // 调用此方法需保证 当前页面有 js-party-select-result-list 和 该id 的隐藏域
        layer('examine', 'setCondition', {
            id: id,
            val: value,
            mid: mid
        })
    })
    // 确认保存条件
    $(document).on('click', '#setConditionBtn', this, function () {
        const rules = {
            'name': '条件名称',
            'level': '优先级',
            'staff[]': '申请人',
            'field': '字段',
            'range': '范围',
            'value': '属性'
        }
        let params = $('[name="examineSetConditionForm"]').serializeArray()
        let object = {},
            flag = false
        let data, id, msg = ''
        $.each(params, function (index, field) {
            if (field.value.length > 0) {
                object[field.name] = field.value
                id = (field.name === 'id') ? field.value : ''
            } else {
                if (object['field'] === 'null') {
                    object['range'] = '等于'
                    object['value'] = '无'
                } else {
                    flag = true
                    msg = rules[field.name] + '不能为空' + '<br>'
                    return false
                }
            }
        })
        if (flag === true) {
            warn(msg)
            return
        }
        let jsResultList = $(this).parents('form').find('.js-party-select-result-list')
        let namestr = ''
        if (jsResultList.length > 0) {
            namestr = jsResultList.html()
        } else {
            namestr = $('.js-party-select-result-list').html()
        }
        // 整合名称
        const spanReg = new RegExp('</?|span>', 'g')
        object['staffName'] = namestr.replace(spanReg, '')

        data = JSON.stringify(object)
        let resultHtml = `
            <p>${rules['level']}：${object['level']}</p>
            <p class="staff-text">${rules['staff[]']}：${namestr}</p>
            <p>${object['field'] === 'null' ? '无需条件' : '：' + object['range'] + ' ' + object['value']}</p>
        `
        // 将转换后的json 回写
        $('#' + id).val(data)
        const divObj = $('#div' + id)
        divObj.html(resultHtml)
        // 移除员工选择器 及提示语
        divObj.prevAll('p.placeholder').remove()
        $('#examineSetCondition').remove()
        // 回写结果

    })

    // 选择人
    $(document).on('click', '#staffSel, #setApplicant, #staffSelector, #setPosition', this, function () {
        let name = $(this).data('name')===undefined?'staff':$(this).data('name'),
            parent = $(this).parents('div#'+name+'-box'),
            obj = parent.find('[name="'+name+'[]"]'),
            id = rand()
        if (obj.length > 0) {
            id = obj.attr('id')
        } else {
            let tpl = `
            <input id="${id}" type="hidden" name="staff[]">`
            parent.append(tpl)
        }
        let params = {}

        // 类型
        switch ($(this).attr('id')) {
            case 'setApplicant':
                params = {
                    id: id,
                    all: true
                }
                break;
            case 'staffSelector'://单独作为员工选择器时
                params = {
                    id: id,
                    all: true,
                    other: 'selector',
                }
                break;
            case 'setPosition':
                params = {
                    id: id,
                    range: 'job',
                    all: true
                }
                break;
            default:
                params = {
                    id: id,
                    range: 'staff',
                    all: true
                }
                break;
        }
        // 调用此方法需保证 当前页面有 js-party-select-result-list 和 该id 的隐藏域
        layer('examine', 'orgTree', params)
        $(this).find('.placeholder').remove()
    })


    // 节点 - 新增人员
    $(document).on('click', '.add-node-popover-item', this, function () {
        const classify = $(this).attr('data-click')
        let type, title, text, icon
        let id = rand()
        switch (classify) {
            case 'approver':
                type = 'approver'
                title = '审批人'
                icon = decodeURIComponent('\ue8ef')
                break
            case 'notifier':
                type = 'notifier'
                title = '抄送人'
                icon = decodeURIComponent('\ue93b')
                break
            default:
                break
        }
        // 提示语
        text = '选择' + title
        // 循环替换
        const array = ['type', 'title', 'text', 'icon', 'id']
        let approver = approverTpl
        for (const key in array) {
            let reg = new RegExp('{{' + array[key] + '}}', 'g')
            approver = approver.replace(reg, eval(array[key]))
        }
        // 节点插入模板并移除提示框
        $(this).parents('.condition-node').after(approver)
        $(this).parents('.tooltip').remove()
    })

    // 删除审批人或抄送人
    $(document).on('click', '[data-click="staff-close"]', this, function () {
        $(this).parents('.condition-node').remove()
    })

    // 选择审批人 选择抄送人
    $(document).on('click', '[data-click="approver-setting"], [data-click="notifier-setting"]', this, function () {
        let click = $(this).attr('data-click'),
            parent = $(this).find('div.text'),
            obj = parent.find('[name="node[]"]'),
            id = obj.attr('id'),
            value = obj.val()
        let fun = (click.indexOf('approver') > -1) ? 'setApprover' : 'setNotifier'
        // 调用此方法需保证 当前页面有 js-party-select-result-list 和 该id 的隐藏域
        layer('examine', fun, {
            id: id,
            val: value
        })
        $(this).find('.placeholder').remove()
    })

    // 审批人员 抄送人 确认保存
    $(document).on('click', '#setApproverBtn, #setNotifierBtn', this, function () {
        let act = $(this).attr('id'),
            opt, form
        let rules = {}
        let params
        // 审核操作
        if (act.indexOf('setApproverBtn') > -1) {
            rules = {
                'type': '类型',
                'staff[]': '审核人',
                'value': '属性',
                'multiType': '多人审批',
                'isAuto': '自动审批',
            }
            form = 'examineSetApproverForm'
            opt = '审核'
        } else {
            rules = {
                'type': '类型',
                'staff[]': '抄送人',
                'value': '属性',
            }
            form = 'examineSetNotifierForm'
            opt = '抄送'
        }
        params = $('[name="' + form + '"]').serializeArray()
        let data, id, object = {},
            msg = '',
            flag = false
        console.log(params)
        $.each(params, function (index, field) {
            if (field.value.length > 0) {
                object[field.name] = field.value
                id = (field.name === 'id') ? field.value : ''
            } else {
                if (field.name === 'staff[]' || field.name === 'value') {
                    return true
                }
                flag = true
                msg = rules[field.name] + '不能为空' + '<br>'
                return false
            }
        })
        if (flag === true) {
            warn(msg)
            return
        }
        // 条件id
        let cidObj = $('#' + object['id']).parents('div.col-box').find('[name="cid"]')
        if (cidObj.length === 0) {
            warn('请先完善条件信息')
            return
        }
        object['cid'] = cidObj.val()
        // 方式
        object['form'] = (opt === '审核') ? 'approver' : 'notifier'
        // 人员信息
        let staffString = $('#name' + object['id']).html()
        object['staffName'] = parseStaffName(staffString)
        data = JSON.stringify(object)
        // 移除选择器
        let resultHtml, removeObj
        if (opt === '审核') {
            resultHtml = `
                <p>${rules['type']}：${object['type']}</p>
                <p>${rules['multiType']}：${object['multiType']}</p>
                <p>${rules['isAuto']}：${object['isAuto']}</p>
                <p class="staff-text">${rules['staff[]']}：${staffString ? staffString : object['value']}</p>
            `
            removeObj = 'examineSetApprover'
        } else {
            resultHtml = `
                <p>${rules['type']}：${object['type']}</p>
                <p class="staff-text">${rules['staff[]']}：${staffString ? staffString : object['value']}</p>
            `
            removeObj = 'examineSetNotifier'
        }
        // 将转换后的json 回写
        $('#' + id).val(data)
        $('#div' + id).html(resultHtml)
        $('#' + removeObj).remove()
    })

    // 解析员工名称
    function parseStaffName(string) {
        // 人员
        const spanReg = new RegExp('</?|span>', 'g')
        return string.replace(spanReg, '')
    }


})


// 指定上级
const appoint = [
    '直接上级',
    '第二级上级',
    '第三级上级',
    '第四级上级',
    '第五级上级',
    '第六级上级',
    '第七级上级',
    '第八级上级',
    '第九级上级',
    '第十级上级',
]

// 连续上级
const continuous = [
    '最高上级',
    '第二级上级',
    '第三级上级',
    '第四级上级',
    '第五级上级',
    '第六级上级',
    '第七级上级',
    '第八级上级',
    '第九级上级',
    '第十级上级',
]

/**
 * 随机字符
 */
function rand(length = 20) {
    let string = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    let x = string.length
    let temp = ''
    for (let i = 0; i < length; i++) {
        temp += string.charAt(Math.floor(Math.random() * x));
    }
    return temp;
}


// 设置 审批人类型
function setApproverType(obj) {
    let val = $(obj).val(),
        box = $(obj).parents().find('#staff-box'),
        boxAppend = box.find('#approver-append'),
        category = $(obj).parents('div.layerList').find('#approver-category'),
        tpl = ''
    // 先清空
    box.find('.js-party-select-result-list').empty()
    box.find('[name="staff[]"]').val('')
    boxAppend.empty()
    switch (val) {
        case '指定成员':
            tpl = `<span class="spanButton" id="staffSel">选择</span>`
            break;
        case '指定上级':
            tpl += `<select name="value" class="text"><option value="">--请选择--</option>`
            appoint.forEach(ele => {
                if (ele.length > 0) {
                    tpl += `<option value="${ele}">${ele}</option>`
                }
            });
            tpl += `</select>`
            break;
        case '连续多级上级':
            tpl += `<select name="value" class="text"><option value="">--请选择--</option>`
            continuous.forEach(ele => {
                if (ele.length > 0) {
                    tpl += `<option value="${ele}">${ele}</option>`
                }
            });
            tpl += `</select>`
            break;
        case '指定职位':
            tpl = `<span class="spanButton" id="setPosition">选择</span>`
            break;
        case '审批人自选':
            tpl = `
            可选范围：
            <label class="radioLabel">&nbsp;<input name="value" type="radio" value="不限范围">&nbsp;不限范围</label>
            <label class="radioLabel">&nbsp;<input name="value" type="radio" value="指定范围" id="staffSel">&nbsp;指定范围</label>
            `
            break;
        case '部门负责人':
            tpl = `
            可选类型：
            <label class="radioLabel">&nbsp;<input name="value" type="radio" value="发起人部门负责人">&nbsp;发起人部门负责人</label>
            <label class="radioLabel">&nbsp;<input name="value" type="radio" value="成员部门负责人">&nbsp;成员部门负责人</label>
            <div class="tip-component" id="tip-component">i</div>
            <script>
//开源地址https://github.com/atomiks/tippyjs
tippy("#tip-component", {
  // default
  content: '发起人部门负责人：将由提交人所在部门的负责人审批；成员部门负责人：将由被代提交人员的部门负责人审批',
});
</script>
            `
            break;
        default:
            warn('类型错误')
            return false
    }
    category.html(`${val}`)
    boxAppend.append(tpl)
}

$(document).on('click', '#materialSelector', this, function () {
    let parent = $(this).parents('div#staff-box'),
        obj = parent.find('[name="materialIds[]"]'),
        id = rand()
    if (obj.length > 0) {
        id = obj.attr('id')
    } else {
        let tpl = `
            <input id="${id}" type="hidden" name="materialIds[]">`
        parent.append(tpl)
    }
    let params = {}

    // 类型
    switch ($(this).attr('id')) {
        case 'materialSelector'://单独作为员工选择器时
            params = {
                id: id,
                all: true,
                other: 'selector',
            }
            break;
        default:
            params = {
                id: id,
                range: 'staff',
                all: true
            }

            break;
    }
    // 调用此方法需保证 当前页面有 js-party-select-result-list 和 该id 的隐藏域
    layer('examine', 'materialTree', params)
    $(this).find('.placeholder').remove()
})
